package com.trace.demo.controller;

import com.trace.demo.entity.Order;
import com.trace.demo.repository.OrderRepository;
import com.trace.demo.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 支付控制器 - 处理订单支付相关请求
 */
@RestController
@RequestMapping("/api/payment")
public class PaymentController {

    private final OrderRepository orderRepository;

    @Autowired
    public PaymentController(OrderRepository orderRepository) {
        this.orderRepository = orderRepository;
    }

    /**
     * 处理支付请求
     * @param paymentData 包含订单号和支付方式的数据
     * @return 支付结果
     */
    @PostMapping("/pay")
    public ResponseEntity<ApiResponse<Map<String, Object>>> processPayment(@RequestBody Map<String, Object> paymentData) {
        String orderNumber = (String) paymentData.get("orderNumber");
        String paymentMethod = (String) paymentData.get("paymentMethod");
        
        // 检查参数
        if (orderNumber == null || orderNumber.isEmpty()) {
            return ResponseEntity.badRequest()
                    .body(new ApiResponse<>(false, "订单号不能为空", null));
        }
        
        // 查找订单
        Optional<Order> orderOpt = orderRepository.findByOrderNumber(orderNumber);
        
        if (!orderOpt.isPresent()) {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body(new ApiResponse<>(false, "订单不存在", null));
        }
        
        Order order = orderOpt.get();
        
        // 模拟支付处理
        // 在实际应用中，这里会调用支付网关API
        
        // 更新订单状态为已支付
        order.setStatus(Order.OrderStatus.PAID);
        order.setPaymentDate(LocalDateTime.now());
        order.setPaymentMethod(paymentMethod != null ? paymentMethod : "银行转账");
        
        // 保存订单
        Order updatedOrder = orderRepository.save(order);
        
        // 构建响应
        Map<String, Object> response = new HashMap<>();
        response.put("orderNumber", updatedOrder.getOrderNumber());
        response.put("status", updatedOrder.getStatus().toString());
        response.put("paymentDate", updatedOrder.getPaymentDate());
        response.put("paymentMethod", updatedOrder.getPaymentMethod());
        response.put("message", "支付成功");
        
        return ResponseEntity.ok(new ApiResponse<>(true, "支付处理成功", response));
    }
    
    /**
     * 获取支付方式列表
     * @return 支付方式列表
     */
    @GetMapping("/methods")
    public ResponseEntity<ApiResponse<Map<String, Object>>> getPaymentMethods() {
        Map<String, Object> methods = new HashMap<>();
        
        // 添加支付方式
        methods.put("alipay", "支付宝");
        methods.put("wechat", "微信支付");
        methods.put("bank", "银行转账");
        
        return ResponseEntity.ok(new ApiResponse<>(true, "获取支付方式成功", methods));
    }
    
    /**
     * 处理支付回调（模拟）
     * @param callbackData 回调数据
     * @return 处理结果
     */
    @PostMapping("/callback")
    public ResponseEntity<String> handlePaymentCallback(@RequestBody Map<String, Object> callbackData) {
        // 模拟处理支付回调
        // 实际应用中，这里会验证签名，确认交易状态等
        
        String orderNumber = (String) callbackData.get("orderNumber");
        String status = (String) callbackData.get("status");
        
        // 简单日志
        System.out.println("收到支付回调: 订单=" + orderNumber + ", 状态=" + status);
        
        // 返回成功
        return ResponseEntity.ok("success");
    }
} 